package com.sim.server.command.handler;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.sim.core.ImChannelContext;
import com.sim.core.ImPacket;
import com.sim.core.ImStatus;
import com.sim.core.exception.ImException;
import com.sim.core.packets.Command;
import com.sim.core.packets.InviteInfoBody;
import com.sim.core.packets.InviteReqBody;
import com.sim.core.packets.RespBody;
import com.sim.core.utils.JsonKit;
import com.sim.server.SimServerAPI;
import com.sim.server.command.AbstractCmdHandler;
import com.sim.server.protocol.ProtocolManager;

/**
 * @Description 邀请CMD处理器
 * @Author zl
 * @Date 2021/7/22 0022
 * @Version 1.0
 **/
public class InviteReqHandler extends AbstractCmdHandler {

    @Override
    public Command command() {
        return Command.COMMAND_INVITE_REQ;
    }

    /**
     * 邀请逻辑：向被邀请用户发送私聊消息，消息内容的 Command 为 Command.COMMAND_INVITE_REQ
     * 前端根据结果展示，用户选择加入小组就调用 加入小组的CMD处理器
     * @param imPacket
     * @param imChannelContext
     * @return
     * @throws ImException
     */
    @Override
    public ImPacket handler(ImPacket imPacket, ImChannelContext imChannelContext) throws ImException {
        if (imPacket.getBody() == null) {
            RespBody respBody = new RespBody(Command.COMMAND_INVITE_RESP, ImStatus.C10029);
            return ProtocolManager.Converter.respPacket(respBody, imChannelContext);
        }
        InviteReqBody reqBody = JsonKit.toBean(imPacket.getBody(), InviteReqBody.class);
        if (StrUtil.isBlank(reqBody.getUserId()) || CollectionUtil.isEmpty(reqBody.getInviteUsers())){
            RespBody respBody = new RespBody(Command.COMMAND_INVITE_RESP, ImStatus.C10029);
            return ProtocolManager.Converter.respPacket(respBody, imChannelContext);
        }

        reqBody.getInviteUsers().stream().distinct().forEach(toUser -> {
            InviteInfoBody inviteInfoBody = InviteInfoBody.builder()
                    .fromUserId(reqBody.getUserId())
                    .fromUserName(reqBody.getUserName())
                    .toUserId(toUser.getToUserId())
                    .toUserName(toUser.getToUserName())
                    .groupId(reqBody.getGroupId())
                    .groupName(reqBody.getGroupName())
                    .build();
            ImPacket inviteInfo = new ImPacket(Command.COMMAND_CHAT_REQ, new RespBody(Command.COMMAND_INVITE_REQ, inviteInfoBody).toByte());
            SimServerAPI.sendToUser(toUser.getToUserId(), inviteInfo);
        });

        RespBody respBody = new RespBody(Command.COMMAND_INVITE_RESP, ImStatus.C10030);
        return ProtocolManager.Converter.respPacket(respBody, imChannelContext);
    }

}
